import { ElMessage } from 'element-plus';
import type { MessageHandler } from 'element-plus';
import { defineComponent } from 'vue';

type MessageOptions = {
  message: string;
  type?: 'success' | 'warning' | 'info' | 'error';
  duration?: number;
  showClose?: boolean;
  center?: boolean;
  grouping?: boolean;
  dangerouslyUseHTMLString?: boolean;
  customClass?: string;
  iconClass?: string;
  onClose?: () => void;
  offset?: number;
};

export default class Message {
  private _message = ElMessage;
  private _hander: MessageHandler | null = null;

  info(msg: string | MessageOptions) {
    const message = typeof msg === 'string' ? msg : msg.message;
    const type = typeof msg === 'string' ? 'info' : msg.type;
    const options = typeof msg === 'string' ? {} : msg;

    this._hander = this._message(
      Object.assign(
        {
          message,
          type,
          duration: 3000,
          showClose: true,
          center: true,
          grouping: true,
          customClass: 'message'
        },
        options
      )
    );
  }

  loading(message: string = 'loading...') {
    this._hander = this._message({
      icon: LoadingSpinner,
      type: 'info',
      plain: true,
      message,
      duration: 0
    });
  }

  success(message: string) {
    this._message.success(message || '操作成功');
  }

  error(message: string) {
    this._message.error(message || '操作失败');
  }

  warn(message: string) {
    this._message.warning(message || '操作警告');
  }

  destroy() {
    this._hander?.close();
  }
}

export const message = new Message();

export const LoadingSpinner = defineComponent({
  name: 'LoadingSpinner',
  render() {
    return (
      <>
        <div class="a-spinner" role="spinner">
          <div class="a-spinner-icon"></div>
        </div>
        <style jsx>
          {`
            .a-spinner {
              display: block;
              z-index: 1031;
            }

            .a-spinner-icon {
              width: 16px;
              height: 16px;
              box-sizing: border-box;
              border-color: #29d transparent transparent #29d;
              border-style: solid;
              border-width: 2px;
              border-radius: 50%;
              -webkit-animation: nprogress-spinner 0.4s linear infinite;
              animation: nprogress-spinner 0.4s linear infinite;
            }
          `}
        </style>
      </>
    );
  }
});
